package com.dianrui.firemenmonitor.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.dianrui.firemenmonitor.Constant;
import com.dianrui.firemenmonitor.R;
import com.dianrui.firemenmonitor.event.NewMobile;
import com.dianrui.firemenmonitor.util.OkHttpUtils;
import com.dianrui.firemenmonitor.util.SharedUtil;
import com.dianrui.firemenmonitor.util.StringUtils;
import com.dianrui.firemenmonitor.util.ToastUtil;
import com.dianrui.firemenmonitor.util.Url;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {
    boolean isHide = false;
    private ProgressDialog mProgressDialog;

    @BindView(R.id.login_mobile_ed)
    EditText loginMobileEd;
    @BindView(R.id.login_pwd_ed)
    EditText loginPwdEd;
    @BindView(R.id.current_pwd_eyes)
    ImageView currentPwdEyes;

    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        customInit(R.color.blue_518bfa);
        if (!StringUtils.isEmpty(spUtils.getString("Id"))) {
            JumpActivitys(MainActivity.class);
            finish();
        }
        mProgressDialog = new ProgressDialog(LoginActivity.this);
        currentPwdEyes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isHide) {
                    isHide = false;
                    currentPwdEyes.setImageResource(R.mipmap.logo_eyes_open);
                    HideReturnsTransformationMethod method = HideReturnsTransformationMethod.getInstance();
                    loginPwdEd.setTransformationMethod(method);
                    loginPwdEd.setSelection(loginPwdEd.length());
                } else {
                    isHide = true;
                    currentPwdEyes.setImageResource(R.mipmap.logo_eyes_close);
                    TransformationMethod method = PasswordTransformationMethod.getInstance();
                    loginPwdEd.setTransformationMethod(method);
                    loginPwdEd.setSelection(loginPwdEd.length());
                }
            }
        });
        loginMobileEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(loginMobileEd.getWindowToken(), 0);
                    }
                }
            }
        });
        loginPwdEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 6) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(loginPwdEd.getWindowToken(), 0);
                    }
                }
            }
        });
    }


    @OnClick({R.id.login_btn, R.id.forgetpwd,R.id.txt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                if (StringUtils.isEmpty(loginMobileEd.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.login_mobile_hint));
                } else if (StringUtils.isEmpty(loginPwdEd.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.login_password_hint));
                } else {
                    startLogin();
                }
                break;
            case R.id.forgetpwd:
                JumpActivitys(ForgetPasswordActivity.class);
                break;

            case R.id.txt:
                startActivity(new Intent(LoginActivity.this, WebViewActivity.class).putExtra("url", Constant.USE));
                break;

                default:
                    break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(NewMobile newMobile) {
        loginMobileEd.setText(newMobile.number);
    }

    private void startLogin() {
        mProgressDialog.setMessage(getString(R.string.login_txt9));
        mProgressDialog.show();
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("mobilealarm",loginMobileEd.getText().toString().trim());
        jsonObject.addProperty("password",loginPwdEd.getText().toString().trim());
        OkHttpUtils.getInstance().postRequests(Url.LOGIN, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    mProgressDialog.dismiss();
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                spUtils.put("Id", jsonObject.optJSONObject("data").optJSONObject("userinfo").optString("Id"));
                                spUtils.put("username", jsonObject.optJSONObject("data").optJSONObject("userinfo").optString("username"));
                                spUtils.put("userimg", jsonObject.optJSONObject("data").optJSONObject("userinfo").optString("userimg"));
                                spUtils.put("phone", jsonObject.optJSONObject("data").optJSONObject("userinfo").optString("phone"));
                                spUtils.put("policesignal", jsonObject.optJSONObject("data").optJSONObject("userinfo").optString("policesignal"));
                                SharedUtil.setToken(jsonObject.optJSONObject("data").optJSONObject("userinfo").optString("token"));
                                JumpActivitys(MainActivity.class);
                                finish();

                            }else {
                                mProgressDialog.dismiss();
                                ToastUtil.showToast(jsonObject.optString("msg"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mProgressDialog != null  && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }
}
